import React, { useEffect, useState } from 'react'
import WalletConnect from "@walletconnect/client";
import QRCodeModal from "@walletconnect/qrcode-modal";

export default function Index() {
    const [isWallectConnect, setIsWallectConnect] = useState(true)     // 总开关：代表是不是使用WallectConnect 来连接   这里的初始值需要用cookie 或 redux来获取
    const [textVal, setTextVal] = useState('暂无连接钱包')
    const [web3Info, setWeb3Info] = useState(null)

    useEffect(() => {
        console.log(web3Info)
        if (!web3Info) return
        setTextVal(`    账户信息：
                账号：${web3Info.accout}        chainId: ${web3Info.chainId}`)
    }, [web3Info])

    useEffect(() => {
        // 根据 isWallectConnect 来判断是否要初始化WallectConnect
        if (!isWallectConnect) return false
        // 初始化连接
        initWeb3()
    }, [isWallectConnect])


    // 初始化
    const initWeb3 = async () => {
        // 实例化连接参数
        const connector = new WalletConnect({
            bridge: "https://bridge.walletconnect.org", // Required
            qrcodeModal: QRCodeModal,
        });


        subEvent(connector)
        console.log(connector)

        // 判断连接状态
        if (connector.connected) {
            // create new session
            setTextVal('加载中...')
            setWeb3Info({
                isConnect: true,
                accout: connector._accounts[0],
                chainId: connector._chainId
            })
        } else {
            setTextVal('暂未连接钱包')
            connector.createSession();
        }

    }
    // 订阅事件
    const subEvent = (connector) => {
        // Subscribe to connection events
        connector.on("connect", (error, payload) => {
            if (error) {
                throw error;
            }

            // Get provided accounts and chainId
            const { accounts, chainId } = payload.params[0];
            setWeb3Info({
                isConnect: true,
                accout: accounts,
                chainId: chainId
            })
        });

        connector.on("session_update", (error, payload) => {
            if (error) {
                throw error;
            }

            // Get updated accounts and chainId
            const { accounts, chainId } = payload.params[0];
            setWeb3Info({
                isConnect: true,
                accout: accounts,
                chainId: chainId
            })
        });

        connector.on("disconnect", (error, _payload) => {
            if (error) {
                throw error;
            }

            // Delete connector
            setWeb3Info({
                isConnect: false,
                accout: null,
                chainId: null
            })
        });
    }

    const handelClickConnect = () => {
        setIsWallectConnect(true)
    }

    const handelClickBreak = () => {
        setIsWallectConnect(false)
        setTextVal('断开连接（模拟）')
    }

    return (
        <div>
            <h3>钱包信息</h3>
            <textarea value={textVal} name="" id="" cols="100" rows="5" disabled={true}></textarea>

            <br /> <br />
            <button onClick={handelClickConnect}>连接 WallectConnect</button>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <button onClick={handelClickBreak}>断开连接</button>
        </div>
    )
}
